<template>
  <div class="flex" style="width: 100%; flex-direction: column; height: 100%">
    <div class="flex box">
      <div style="flex: 1; overflow: hidden; position: relative; margin-bottom: 10px" ref="chartRefABox">
        <div style="position: absolute; top: 20px; left: 20px; font-size: 15px; color: #00D1FF; font-weight: bold">固定资产
        </div>
        <div ref="chartRefA" class="chart-container" style="position: relative"></div>
      </div>
      <div style="flex: 1; position: relative">
        <div style="position: absolute; top: 20px; left: 20px; font-size: 15px; color: #00D1FF; font-weight: bold">文印数据
        </div>
        <div ref="chartRefB" class="chart-container"></div>

        <el-date-picker @change="handleDateChange" v-model="wenYDateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 180px; position: absolute; top: 50px; right: 20px" size="small" type="daterange" range-separator="-" />
      </div>
      <!-- <div style="flex: 1; position: relative">
        <div style="position: absolute; top: 20px; left: 20px; font-size: 15px; color: #00D1FF; font-weight: bold">用电分布
        </div>
        <div ref="chartRefC" class="chart-container"></div>
      </div> -->
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,onUnmounted } from "vue";
import * as echarts from "echarts";
import * as leaderApi from "@/api/leaders";

let chartRefABox = ref(null);
let chartRefA = ref(null);
let chartA = ref(null);
let chartRefB = ref(null);
let chartB = ref(null);
let chartRefC = ref(null);
let chartC = ref(null);

// 文印数据查询的时间默认时间范围
const wenYDateRange = ref();

// 设置默认时间范围为当前时间往前推6个月
const setDefaultDateRange = async () => {
  const endDate = new Date();
  const startDate = new Date();
  startDate.setMonth(startDate.getMonth() - 6);
  
  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };
  
  wenYDateRange.value = [formatDate(startDate), formatDate(endDate)];

  // 返回 Promise 确保异步操作完成
  return Promise.resolve();
};

// 日期选择完成的回调函数
const handleDateChange = async (value) => {
  if (value && value.length === 2) {
    wenYDateRange.value = [value[0], value[1]];
    dept_cost_stat();
  }
};


// 固定资产
const assets_stat = async () => {
  leaderApi.assets_stat().then((res) => {
    initChartA(res.data);
  });
};

// 文印部门金额统计
const dept_cost_stat = async () => {
  leaderApi.dept_cost_stat(wenYDateRange.value[0], wenYDateRange.value[1]).then((res) => {
    initChartB(res.data);
  });
};

const initChartA_1 = () => {
  const option = {
    title: {
      text: "固定资产",
      top: 20,
      left: 20,
      textStyle: {
        color: "#00D1FF",
        fontSize: 15,
        lineHeight: 10,
      },
    },
    series: {
      type: "sankey",
      label: {
        position: "right",
        textStyle: {
          fontSize: 12,
          color: "#00FFF0",
        },
      },
      layout: "none",
      top: "15%",
      left: "10%",
      right: "10%",
      bottom: "10%",
      emphasis: {
        focus: "adjacency",
      },
      nodeGap: 4,
      nodeWidth: 12,
      data: [
        {
          name: "全部固定资产",
          itemStyle: {
            color: "#226ef8",
          },
        },
        {
          name: "房屋及建筑物",
          itemStyle: {
            color: "#01cbf8",
          },
        },
        {
          name: "通用设备",
          itemStyle: {
            color: "#01f7ae",
          },
        },
        {
          name: "办公用品",
          itemStyle: {
            color: "#f6df03",
          },
        },
        {
          name: "办公楼",
          itemStyle: {
            color: "#0aa6e9",
          },
        },
        {
          name: "教学楼",
          itemStyle: {
            color: "#29c9f5",
          },
        },
        {
          name: "办公设备",
          itemStyle: {
            color: "#6ff7ce",
          },
        },
        {
          name: "电子设备",
          itemStyle: {
            color: "#f6efa9",
          },
        },
        {
          name: "使用",
          itemStyle: {
            color: "#01eba4",
          },
        },
        {
          name: "报废",
          itemStyle: {
            color: "#e47e05",
          },
        },
        {
          name: "维护",
          itemStyle: {
            color: "#f6df02",
          },
        },
        {
          name: "采购",
          itemStyle: {
            color: "#226df7",
          },
        },
      ],
      links: [
        {
          source: "全部固定资产",
          target: "房屋及建筑物",
          value: 10,
        },
        {
          source: "全部固定资产",
          target: "通用设备",
          value: 15,
        },
        {
          source: "全部固定资产",
          target: "办公用品",
          value: 9.5,
        },
        {
          source: "房屋及建筑物",
          target: "办公楼",
          value: 6,
        },
        {
          source: "房屋及建筑物",
          target: "教学楼",
          value: 4,
        },
        {
          source: "通用设备",
          target: "办公设备",
          value: 7.5,
        },
        {
          source: "通用设备",
          target: "电子设备",
          value: 7.5,
        },
        {
          source: "办公用品",
          target: "办公设备",
          value: 1,
        },
        {
          source: "办公用品",
          target: "电子设备",
          value: 1,
        },
        {
          source: "办公楼",
          target: "使用",
          value: 2,
        },
        {
          source: "教学楼",
          target: "使用",
          value: 1,
        },
        {
          source: "办公设备",
          target: "报废",
          value: 2,
        },
        {
          source: "办公用品",
          target: "使用",
          value: 5,
        },
        {
          source: "办公用品",
          target: "采购",
          value: 2,
        },
        {
          source: "办公用品",
          target: "维护",
          value: 1,
        },
        {
          source: "电子设备",
          target: "使用",
          value: 5,
        },
        {
          source: "电子设备",
          target: "采购",
          value: 1,
        },
        {
          source: "电子设备",
          target: "维护",
          value: 1,
        },
      ],
    },
  };
  chartA.value = echarts.init(chartRefA.value);
  chartA.value.setOption(option);
};

let initSankey = false;
const initChartA = (resData) => {

  // 过滤掉空值数据
  const validData = resData.filter(
    (item) => item.level_1_name && item.level_2_name && item.value != null
  );

  const displayData = validData.length > 100 ? validData.slice(0, 20) : validData;

  // 构建节点数据
  const nodes = [];
  const nodeNames = new Set();

  // 添加根节点
  nodeNames.add("全部资产");

  // 添加一级、二级和三级分类节点
  displayData.forEach((item) => {
    nodeNames.add(item.level_1_name);
    nodeNames.add(item.level_2_name);
    nodeNames.add(item.value);
  });

  // 转换为节点数组
  nodeNames.forEach((name) => {
    nodes.push({ name: name });
  });

  // 构建链接数据
  const links = [];

  // 从根节点到一级分类的链接
  const level1Map = {}; // 用于统计一级分类的总值
  displayData.forEach((item) => {
    if (!level1Map[item.level_1_name]) {
      level1Map[item.level_1_name] = 0;
    }
    // 修改：使用 item.total 作为值
    level1Map[item.level_1_name] += parseFloat(item.total) || 0;
  });

  Object.keys(level1Map).forEach((level1Name) => {
    links.push({
      source: "全部资产",
      target: level1Name,
      value: level1Map[level1Name],
    });
  });

  // 从一级分类到二级分类的链接
  const level2Map = {}; // 用于统计二级分类的总值
  displayData.forEach((item) => {
    const key = `${item.level_1_name}-${item.level_2_name}`;
    if (!level2Map[key]) {
      level2Map[key] = 0;
    }
    // 修改：使用 item.total 作为值
    level2Map[key] += parseFloat(item.total) || 0;
  });

  // 去重二级分类链接
  const level2Links = {};
  displayData.forEach((item) => {
    const linkKey = `${item.level_1_name}-${item.level_2_name}`;
    if (!level2Links[linkKey]) {
      level2Links[linkKey] = true;
      links.push({
        source: item.level_1_name,
        target: item.level_2_name,
        // 修改：使用 item.total 作为值
        value: parseFloat(item.total) || 0,
      });
    }
  });

  // 从二级分类到三级分类的链接
  displayData.forEach((item) => {
    links.push({
      source: item.level_2_name,
      target: item.value,
      // 修改：使用 item.total 作为值
      value: parseFloat(item.total) || 0,
    });
  });

  // 过滤掉可能造成循环的链接
  const filteredLinks = links.filter((link) => link.source !== link.target);

  const option = {
    tooltip: {
      trigger: "item",
      triggerOn: "mousemove",
    },
    series: [
      {
        type: "sankey",
        draggable: false,
        label: {
            position: 'right',
            textStyle: {
                fontSize: 12,
                color: '#00FFF0',
            },
        },
        layout: "none",
        top: "5%",
        left: "10%",
        right: "10%",
        bottom: "10%",
        emphasis: {
          focus: "adjacency",
        },
        lineStyle: {
          color: 'source',
        },
        nodeGap: 20,
        nodeWidth: 12,
        // zoom: 2,
        // roam: true,
        // roamTrigger: 'global',
        data: nodes,
        links: filteredLinks,
        // data: [
        //   {
        //     name: "全部固定资产",
        //     itemStyle: {
        //         color: '#226ef8',
        //     },
        //   },
        //   {
        //     name: "房屋及建筑物",
        //     itemStyle: {
        //         color: '#01cbf8',
        //     },
        //   },
        //   {
        //     name: "通用设备",
        //     itemStyle: {
        //         color: '#01f7ae',
        //     },
        //   },
        //   {
        //     name: "办公用品",
        //     itemStyle: {
        //         color: '#f6df03',
        //     },
        //   },
        //   {
        //     name: "办公楼",
        //      itemStyle: {
        //         color: '#0aa6e9',
        //     },
        //   },
        //   {
        //     name: "教学楼",
        //     itemStyle: {
        //         color: '#29c9f5',
        //     },
        //   },
        //   {
        //     name: "办公设备",
        //     itemStyle: {
        //         color: '#6ff7ce',
        //     },
        //   },
        //   {
        //     name: "电子设备",
        //     itemStyle: {
        //         color: '#f6efa9',
        //     },
        //   },
        //   {
        //     name: "使用",
        //     itemStyle: {
        //         color: '#01eba4',
        //     },
        //   },
        //   {
        //     name: "报废",
        //     itemStyle: {
        //         color: '#e47e05',
        //     },
        //   },
        //   {
        //     name: "维护",
        //     itemStyle: {
        //         color: '#f6df02',
        //     },
        //   },
        //   {
        //     name: "采购",
        //     itemStyle: {
        //         color: '#226df7',
        //     },
        //   },
        // ],
        // links: [
        //   {
        //     source: "全部固定资产",
        //     target: "房屋及建筑物",
        //     value: 10,
        //   },
        //   {
        //     source: "全部固定资产",
        //     target: "通用设备",
        //     value: 15,
        //   },
        //   {
        //     source: "全部固定资产",
        //     target: "办公用品",
        //     value: 9.5,
        //   },
        //   {
        //     source: "房屋及建筑物",
        //     target: "办公楼",
        //     value: 6,
        //   },
        //   {
        //     source: "房屋及建筑物",
        //     target: "教学楼",
        //     value: 4,
        //   },
        //   {
        //     source: "通用设备",
        //     target: "办公设备",
        //     value: 7.5,
        //   },
        //   {
        //     source: "通用设备",
        //     target: "电子设备",
        //     value: 7.5,
        //   },
        //   {
        //     source: "办公用品",
        //     target: "办公设备",
        //     value: 1,
        //   },
        //   {
        //     source: "办公用品",
        //     target: "电子设备",
        //     value: 1,
        //   },
        //   {
        //     source: "办公楼",
        //     target: "使用",
        //     value: 2,
        //   },
        //   {
        //     source: "教学楼",
        //     target: "使用",
        //     value: 1,
        //   },
        //   {
        //     source: "办公设备",
        //     target: "报废",
        //     value: 2,
        //   },
        //   {
        //     source: "办公用品",
        //     target: "使用",
        //     value: 5,
        //   },
        //   {
        //     source: "办公用品",
        //     target: "采购",
        //     value: 2,
        //   },
        //   {
        //     source: "办公用品",
        //     target: "维护",
        //     value: 1,
        //   },
        //   {
        //     source: "电子设备",
        //     target: "使用",
        //     value: 5,
        //   },
        //   {
        //     source: "电子设备",
        //     target: "采购",
        //     value: 1,
        //   },
        //   {
        //     source: "电子设备",
        //     target: "维护",
        //     value: 1,
        //   },
        // ],
      },
    ],
  };
  chartA.value = echarts.init(chartRefA.value);
  chartA.value.setOption(option);

  chartA.value.on('rendered', function() {
    const sankeySeries = chartA.value.getModel().getSeriesByType('sankey')[0];
    const graph = sankeySeries.getGraph();
    const nodesByLevel = {};
    graph.eachNode(function(node) {
      const level = node.getLayout().depth;
      nodesByLevel[level] = (nodesByLevel[level] || 0) + 1;
    });
    const MaxLevel = Math.max(...Object.values(nodesByLevel));
    if(!initSankey) {
      chartRefABox.value.style.maxHeight = chartRefABox.value.clientHeight + 'px'
      chartRefA.value.style.height = (MaxLevel * 24) + 'px'
      initSankey = true;
      chartA.value.resize()
    }
  });

  let dragging = false
  let position = null
  chartRefA.value.addEventListener('mousedown', function (e) {
    dragging = true
    position = [e.clientX, e.clientY]
  })
  document.addEventListener('mousemove', function (e) {
    if (dragging === false)  return
    const x = e.clientX
    const y = e.clientY
    const deltaY = y - position[1]
    const top = parseInt(chartRefA.value.style.top || 0)
    chartRefA.value.style.top = top + deltaY + 'px'
    position = [x, y]
  })
  document.addEventListener('mouseup', function (e) {
    dragging = false
  })
};

const initChartB = (resData) => {
  if (chartRefB.value) {
    const existingChart = echarts.getInstanceByDom(chartRefB.value);
    if (existingChart) existingChart.dispose();
  }
  var xData = resData.map(item => item.level_name)
  var seriesData = resData.map(item => item.sum)
  const option = {
    color: ["#00FFF0", "#faff0d"],
    // legend: {
    //   data: ["打印页数", "复印页数"],
    //   top: 40,
    //   textStyle: {
    //     fontSize: 12,
    //     color: function (params) {
    //       return params.color;
    //     },
    //   },
    // },
    grid: {
      top: 100,
      right: 40,
      bottom: 20,
      left: 20,
      containLabel: true,
    },
    tooltip: {},
    xAxis: {
      data: xData,
      axisLine: {
        lineStyle: {
          color: "#0094ff", // ✅ X轴线颜色
        },
      },
      axisTick: {
        lineStyle: {
          color: "#0094ff", // ✅ X轴刻度线颜色
        },
      },
      axisLabel: {
        color: "#fff",
        interval: 0, // 显示所有标签
        rotate: 0,   // 不旋转
        // 使用富文本格式，实现换行显示长标签
        formatter: function(value) {
          // 如果标签文字过长，可以进行换行处理
          if (value.length > 4) {
            return value.substring(0, 4) + '\n' + value.substring(4);
          }
          return value;
        },
        fontSize: 10, // 减小字体大小
      }
    },
    yAxis: {
      type: "value",
      axisLine: {
        lineStyle: {
          color: "#00D1FF",
        },
      },
      splitLine: {
        lineStyle: {
          color: "#0094ff",
        },
      },
      axisLabel: {
        show: true,
      },
    },
    series: [
      {
        name: "",
        type: "bar",
        barWidth: 14,
        data: seriesData,
        label: {
          show: false,
          position: "top",
          formatter: "{c}",
        },
      }
    ],
  };
  chartB.value = echarts.init(chartRefB.value);
  chartB.value.setOption(option);
};
const initChartC = () => {
  if (chartRefC.value) {
    const existingChart = echarts.getInstanceByDom(chartRefC.value);
    if (existingChart) existingChart.dispose();
  }
  const option = {
    color: ["#00ffb2", "#fff509", "#00c1ff", "#00fff1"],
    legend: {
      show: false,
    },
    series: [
      {
        type: "pie",
        roseType: "area",
        radius: ["40%", "70%"],
        center: ["50%", "50%"],
        itemStyle: {
          borderRadius: 8,
        },
        label: {
          formatter: ["{a|{b}}", "{b|{c}kWh}"].join("\n"),
          rich: {
            a: {
              color: "#fff",
              fontSize: 12,
            },
            b: {
              color: "#fff",
              fontSize: 12,
            },
          },
        },
        data: [
          { value: 2, name: "食堂" },
          { value: 2, name: "教学楼" },
          { value: 3, name: "宿舍楼" },
          { value: 1, name: "办公楼" },
        ],
      },
    ],
  };
  chartC.value = echarts.init(chartRefC.value);
  chartC.value.setOption(option);
};
onMounted(async () => {
  await setDefaultDateRange();
  assets_stat();
  dept_cost_stat();
  // initChartC();
  debugger;
  refreshDataInterval();
});

onUnmounted(() => { 
  if(ref_setInterval.value)
  {
    clearInterval(ref_setInterval.value);
    ref_setInterval.value = null;
  }
})

const ref_setInterval = ref(null);
const refreshDataInterval = () => { 
  debugger
  if (import.meta.env.VITE_API_REFRESH_IsEnable == 0) {
    ref_setInterval.value = setInterval(() => {
          assets_stat();
          dept_cost_stat();
    }, import.meta.env.VITE_API_REFRESH_INTERVAL);
  }
}

</script>

<style lang="scss" scoped>
.title {
  color: white;
  width: 100%;
  height: 20px;
  line-height: 20px;
  margin-bottom: 10px;
  text-align: left;
  vertical-align: middle;
  border-left: 4px solid #00a7ff;
  padding-left: 10px;
  border-radius: 2px;
}
.box {
  height: calc(100% - 10px);
  width: 100%;
  margin-top: 10px;
  background-image: url("@/assets/images/profile/leader/bg-2.png");
  background-size: 100% 100%;
  background-position: center;
  background-repeat: no-repeat;
}
::v-deep .el-input__wrapper {
  box-shadow: 0 0 0 1px #00fff0 inset;
  background-color: transparent;
}
::v-deep .el-input__inner {
  color: #00fff0;
}
::v-deep .el-icon {
  color: #00fff0;
}
</style>
